/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.chl.mq._02_workqueue;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import java.util.concurrent.TimeoutException;

/**
 *
 * @author 陈宏亮
 */
public class Worker {

    //队列名称  
    private final static String QUEUE_NAME = NewTask.QUEUE_NAME;

    public static void main(String[] argv) throws java.io.IOException,
            java.lang.InterruptedException, TimeoutException {
        
        //区分不同工作进程的输出  
        String workerName = "职员" + System.currentTimeMillis() % (24 * 60 * 60 * 1000);
        
        //创建连接和频道  
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.2.221");
        factory.setUsername("guest");
        factory.setPassword("guest");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        
        //声明队列  
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(workerName
                + " 等待发工资...");

        QueueingConsumer consumer = new QueueingConsumer(channel);
        
        // false打开应答机制,true关闭。如果不打开应答机制，当worker进程异常退出的时候会丢失消息。
        boolean ack = false;
        
        // 指定消费队列  
        channel.basicConsume(QUEUE_NAME, ack, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());

            System.out.println(workerName + " 接收 '" + message + "'");
            doWork(message);
            System.out.println(workerName + " 完成");
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }

    }

    /**
     * 每个点耗时1s
     *
     * @param task
     * @throws InterruptedException
     */
    private static void doWork(String task) throws InterruptedException {
        for (char ch : task.toCharArray()) {
            if (ch == '.') {
                Thread.sleep(1000);
            }
        }
    }
}
